<template>
  <div id="app-container">
    <el-row justify="space-around">
      <el-col :span="8">
        <el-button type="info" @click="upload(false)" style="width: 90%" v-loading="loading.upload">
          <i class="el-icon-upload" />
        </el-button>
        </el-col>
      <el-col :span="8">
        <el-button type="info" @click="download" style="width: 90%" v-loading="loading.download">
          <i class="el-icon-download" />
        </el-button>
      </el-col>
      <el-col :span="8">
        <el-button type="info" @click="settingDrawer.show = true" style="width: 90%">
          <i class="el-icon-setting" />
        </el-button>
      </el-col>
    </el-row>
    <el-row justify="space-around">
      <el-col :span="12">
        <el-button type="danger" @click="onClickClear" style="width: 90%">
          <i class="el-icon-delete" />
        </el-button>
        </el-col>
      <el-col :span="12">
        <el-button type="success" @click="exportCsv" style="width: 90%">
          <i class="el-icon-document" />
        </el-button>
      </el-col>
    </el-row>
    <el-row justify="space-around">
      <el-col :span="24">
        <el-button type="primary" @click="add" style="width: 90%">
          <i class="el-icon-plus" />
        </el-button>
      </el-col>
    </el-row>
    <span v-if="list.length > 0">
      <el-row v-for="(item, index) in list" :key="item.time" justify="space-around">
        <el-col :span="6">
          <div class="time">
            <div class="time_part">{{tickToDate(item.time)}}</div>
            <div class="time_part">{{tickToTime(item.time)}}</div>
          </div>
        </el-col>
        <el-col :span="12">
          <el-input type="textarea" class="input" v-model="item.content" :autosize="{minRows:1, maxRows:10}" resize="none" />
        </el-col>
        <el-col :span="1">
          <div class="flex_center">
            <el-button type="danger" @click="remove(index)" :circle="true">
              <i class="el-icon-close" />
            </el-button>
          </div>
        </el-col>
      </el-row>
    </span>
    <el-row v-else>
      <el-col :span="24">
        <el-empty description="空空如也"></el-empty>
      </el-col>
    </el-row>

    <el-drawer title="设置" v-model="settingDrawer.show" direction="btt">
      <div style="padding: 20px">
        <el-form :model="setting" :rules="settingDrawer.rules">
          <el-form-item label="同步接口地址" prop="syncUrl">
            <el-input v-model="setting.syncUrl"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>

    <el-dialog
      v-model="mergeDialog.show"
      title="冲突"
      width="calc(min(80%, 600px)"
      :before-close="handleMergeClose"
    >
      <p>合并</p>
      <p>时间：{{tickToDateTime(mergeDialog.time)}}</p>
      <p>旧：{{mergeDialog.oldContent}}</p>
      <p>新：{{mergeDialog.newContent}}</p>
      <template #footer>
        <span class="dialog-footer">
          <el-row justify="space-around">
            <el-col :span="8">
              <el-button type="primary" @click="mergeWith(mergeDialog.oldContent)">【旧】</el-button>
            </el-col>
            <el-col :span="8">
              <el-button type="primary" @click="mergeWith(mergeDialog.newContent)">【新】</el-button>
            </el-col>
            <el-col :span="8">
              <el-button type="warn" @click="abortMerge(); mergeDialog.show = false">取消</el-button>
            </el-col>
          </el-row>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import validUrl from 'valid-url'
import { tickToDateTime, tickToDate, tickToTime, downloadFile } from '@/common/util'
import storage from '@/common/storage'
import sync from '@/api/sync'
import { ElMessage, ElNotification } from 'element-plus'

export default {
  name: "Log",
  data() {
    let checkUrl = (rule, value, callback) => {
      if (validUrl.isUri(value))
        callback()
      else
        return callback(new Error('地址格式有误'))
    }
    return {
      list: [],
      confirmDialog: {
        show: false
      },
      settingDrawer: {
        show: false,
        rules: {
          syncUrl: [{ validator: checkUrl, trigger: 'change' }],
        },
      },
      setting: {
        syncUrl: ''
      },
      loading: {
        upload: false,
        download: false
      },
      mergeDialog: {
        show: false,
        time: null,
        oldContent: '',
        newContent: '',
        callback: null
      },
    }
  },
  mounted() {
    this.loadList()
    this.loadSetting()
  },
  methods: {
    tickToDate,
    tickToTime,
    tickToDateTime,
    loadSetting() {
      this.setting = storage.getObject("logSetting")
    },
    saveSetting() {
      storage.setObject("logSetting", this.setting)
    },
    saveList() {
      storage.setArray("logs", this.list)
    },
    loadList() {
      this.list = storage.getArray("logs")
    },
    add() {
      this.list.splice(0, 0, {
        time: new Date().getTime(),
        content: "",
      })
    },
    remove(index) {
      this.list.splice(index, 1);
    },
    clear() {
      this.list = []
    },
    checkRemoteUrl() {
      if (this.setting.syncUrl) {
        return true;
      } else {
        ElMessage({
          message: "请先设置远程同步接口",
          type: 'error',
          duration: 3000
        })
        return false;
      }
    },
    upload(force = false) {
      let that = this
      if (!this.checkRemoteUrl()) return;
      this.loading.upload = true
      sync.upload(this.setting.syncUrl, this.list, force)
      .then((res) => {
        if (res.code == 101) { // 冲突
          this.$confirm('发现冲突，是否强制覆盖？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            closeOnClickModal: false
          }).then(() => {
            that.upload(true)
          })
        } else {
          ElNotification({
            title: '成功',
            message: '上传成功',
            type: 'success',
            duration: 1000
          })
        }
      })
      .finally(() => {
        this.loading.upload = false
      })
    },
    async download() {
      if (!this.checkRemoteUrl()) return;
      this.loading.download = true
      let res = await sync.download(this.setting.syncUrl)
      let data = await this.mergeData(this.list, res.data)
      if (data === null) {
        console.warn("用户取消合并")
      } else {
        this.list = data
        ElNotification({
          title: '成功',
          message: '下载成功',
          type: 'success',
          duration: 1000
        })
      }
      this.loading.download = false
    },
    async mergeData(data1, data2) { // 简单合并，不同的全部加入，相同的判断冲突，不冲突加入，冲突则手动选择
      data1 = data1.map(e => e).sort((a, b) => b.time - a.time)
      data2 = data2.map(e => e).sort((a, b) => b.time - a.time)
    
      let mergedData = []
      let i = 0, k = 0
      while(true) {
        let newEntry = null
        if (i >= data1.length && k >= data2.length) break;
        else if (i >= data1.length) {
          newEntry = data2[k]
          k++
        }
        else if (k >= data2.length) {
          newEntry = data1[i]
          i++
        }
        else if (data1[i].time == data2[k].time) {
          newEntry = JSON.parse(JSON.stringify(data1[i]))
          // conflict? merge
          if (data1[i].content != data2[k].content) {
            this.mergeDialog.show = true
            this.mergeDialog.time = data1[i].time
            this.mergeDialog.oldContent = data1[i].content
            this.mergeDialog.newContent = data2[k].content

            let abort = false
            await new Promise((resolve) => {
              this.mergeDialog.callback = (data) => {
                resolve(data)
              }
            }).then((data) => {
              if (data === null) {
                abort = true
                return
              }
              newEntry.content = data
            })

            if (abort) return null
          }
          i++, k++
        }
        else if (data1[i].time > data2[k].time) {
          newEntry = data1[i]
          i++
        }
        else {
          newEntry = data2[k]
          k++
        }
        if (!newEntry) throw "未知错误"
        
        console.log(newEntry)
        mergedData.push(newEntry)
      }
      return mergedData
    },
    abortMerge() {
      if (this.mergeDialog.callback) {
        this.mergeDialog.callback(null)
        this.mergeDialog.callback = null
      }
    },
    handleMergeClose(done) {
      this.abortMerge()
      done()
    },
    mergeWith(content) {
      if (this.mergeDialog.callback) {
        this.mergeDialog.callback(content)
        this.mergeDialog.callback = null
      }
      this.mergeDialog.show = false
    },
    onClickClear() {
      let that = this
      this.$confirm('确认清空日志列表？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false
      }).then(() => {
        that.clear()
      })
    },
    exportCsv() {
      // 生成csv
      let csv = "";
      for (let entry of this.list) {
        csv += tickToDateTime(entry.time) + "," + entry.content + "\n";
      }
      var filename = new Date().toLocaleDateString() + "_work.csv";
      downloadFile(csv, filename);
    }
  },
  watch: {
    list: {
      deep: true,
      handler() {
        this.saveList()
      }
    },
    setting: {
      deep: true,
      handler() {
        this.saveSetting()
      }
    }
  },
};
</script>

<style scoped>
.flex_center {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.el-row {
  margin: 5px;
  width: 100%;
}
.el-col {
  display: flex;
  justify-content: center;
  align-items: center;
}
.time {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
  border-radius: 10px;
  background: rgb(129, 106, 133);
  font-family: consolas;
  height: 34px;
  padding: 5px 10px;
  color: white;
  user-select: none;

  overflow: hidden;
}
.time_part {
  margin: 0 5px;
  flex-shrink: 0;
}
.input {
  resize: none;
}
</style>
